package com.hornsun.member.API;

import com.google.common.base.Preconditions;
import com.hornsun.domain.dbo.Member;
import com.hornsun.repository.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 编译中... on 2018/1/27.
 */
@RestController
@RequestMapping("api/member")
public class MemberAPI {
    @Autowired
    private MemberRepository memberRepository;

    /**
     * 新增会员
     * @param member
     */
    @PostMapping("/addMember")
    //@PostMapping("/member")
    public ResponseEntity<?> addMember(@RequestParam Member member){
        member.setMemberGuid(UUID.randomUUID().toString());
        memberRepository.insertMember(member);
            return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 修改会员信息
     *
     * @param member
     */
    @PutMapping("/updateMember")
    public ResponseEntity<?> updateMember(@RequestParam Member member){
        memberRepository.updateMember(member);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除会员
     */
    @PostMapping("/deleteMember")
    public ResponseEntity<?> deleteMember(@RequestParam String guid){
            memberRepository.deleteMember(guid);
            return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 模糊查询会员
     * 使用正则解析参数，若是电话号码则精确查询，若是会员名则返回所有此名字的用户
     * @param example
     * @return
     */
    @GetMapping("/queryMemberByExample")
    public ResponseEntity<?> queryMember(@RequestParam("example")String example ){
        String regExp = "^1\\d{10}$";
        Pattern pattern = Pattern.compile(regExp);
        Matcher matcher = pattern.matcher(example);
        List<Member> list ;
        if (matcher.matches()){
            list = queryMemberByMobile(example);
        }else{
            list = queryMemberByName(example);
        }
        if(list!=null) {
            return new ResponseEntity<List<Member>>(list, HttpStatus.OK);
        }else{
            return new ResponseEntity<Object>("查找失败！",HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    private List<Member> queryMemberByMobile(@RequestParam("mobile") String mobile){
        Preconditions.checkNotNull(mobile);
        return memberRepository.getMemberByMobile(mobile);
    }

    private List<Member> queryMemberByName(@RequestParam("name") String name){
        Preconditions.checkNotNull(name);
        return memberRepository.getMemberByName(name);
    }

}
